import { onMounted, onUnmounted, Ref, ref } from 'vue';

export function useTimer(callback: (date: Date) => void, ms: number = 1000): void {
  let timerID: any;

  onMounted(() => {
    timerID = setInterval(() => {
      if (callback != null) {
        callback(new Date());
      }
    }, ms)
  });

  onUnmounted(() => clearInterval(timerID));
}

export function useEventListener(target: any, event: string, callback: (event: any) => void): void {
  onMounted(() => target.addEventListener(event, callback));
  onUnmounted(() => target.removeEventListener(event, callback));
}

export function useWindowInnerSize(param?: { heightOffset?: number | null, widthOffset?: number | null } | null): Ref<{ height: number, width: number }> {
  const defalutOffset: number = 0;

  const size = ref({
    height: window.innerHeight - (param?.heightOffset ?? defalutOffset),
    width: window.innerWidth - (param?.widthOffset ?? defalutOffset),
  });

  useEventListener(window, 'resize', () => {
    size.value = {
      height: window.innerHeight - (param?.heightOffset ?? defalutOffset),
      width: window.innerWidth - (param?.widthOffset ?? defalutOffset),
    };
  });

  return size;
}